package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解析, 从请求中拿到参数
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        //校验账号和密码是否正确
        //如果正确, 跳转到主页
        //此处应该从数据库中, 根据用户名, 获取用户的信息, 去数据库比对
        if (!("admin".equals(name) && "123456".equals(password))){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("账号或者密码错误");
            return;
        }
        //第一次登录, session为null, 我们创建一个session, 把用户的信息放进去
        HttpSession session = req.getSession(true);
        session.setAttribute("name",name);
        //session.setAttribute(“key”,value);是session设置值的方法,原理同java中的HashMap的键值对,意思也就是key现在为“user”;存放的值为userName
        //名称、对象
        session.setAttribute("loginCount",0);
        resp.sendRedirect("index");//重定向跳转到index页面
    }
}
